﻿using MyControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ModbusLib;
using Models;
using DAL;
using static DAL.IniConfigHelper;
using System.IO.Ports;
using xktComm;

namespace 温湿度传感器
{
    public partial class Form1 : Form
    {

        ModbusLib.ModbusRtu modbus = new ModbusLib.ModbusRtu();
        Config config;
        private Dictionary<byte, ThMonitorDb> CurrentValue = new Dictionary<byte, ThMonitorDb>();
        private System.Threading.CancellationTokenSource cts;
        private System.Windows.Forms.Timer updateTimer = new Timer();

        private string fileName = Application.StartupPath + "\\config\\config.ini";
        public Form1()
        {
            InitializeComponent();
            config = GetIniValues();
            //config = new Config()
            //{
            //    PortName = "COM10",
            //    BaudRate = 9600,
            //    Parity = System.IO.Ports.Parity.None,
            //    DataBits = 8,
            //    StopBits = System.IO.Ports.StopBits.One,
            //    SlaveId1 = 1,
            //    SlaveId2 = 2,
            //    SlaveId3 = 3,
            //    SlaveId4 = 4
                
            //};
            try
            {
                modbus.Connect(config.PortName, config.BaudRate, config.Parity, config.DataBits, config.StopBits);
            }
            catch (Exception ex)
            {

                MessageBox.Show("连接失败" + ex.Message);
                return;
            }

            MessageBox.Show("成功");

            cts = new System.Threading.CancellationTokenSource();
            Task.Run(new Action(() =>
            {
                Communication();
            }),cts.Token);
            updateTimer.Interval = 200;
            updateTimer.Tick += UpdateTimer_Tick;
            updateTimer.Start();


        }

        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            if (CurrentValue.ContainsKey(config.SlaveId1))
            {
                thMonitor1.TemperatureValue = CurrentValue[config.SlaveId1].TemperatureValue;
                thMonitor1.HumidityValue = CurrentValue[config.SlaveId1].HumidityValue;
            }

            if (CurrentValue.ContainsKey(config.SlaveId2))
            {
                thMonitor2.TemperatureValue = CurrentValue[config.SlaveId2].TemperatureValue;
                thMonitor2.HumidityValue = CurrentValue[config.SlaveId2].HumidityValue;
            }
            if (CurrentValue.ContainsKey(config.SlaveId3))
            {
                thMonitor3.TemperatureValue = CurrentValue[config.SlaveId3].TemperatureValue;
                thMonitor3.HumidityValue = CurrentValue[config.SlaveId3].HumidityValue;
            }
            if (CurrentValue.ContainsKey(config.SlaveId4))
            {
                thMonitor4.TemperatureValue = CurrentValue[config.SlaveId4].TemperatureValue;
                thMonitor4.HumidityValue = CurrentValue[config.SlaveId4].HumidityValue;
            }
        }

        private void Communication()
        {
            while (!cts.IsCancellationRequested)
            {
                GetValues(config.SlaveId1);
                GetValues(config.SlaveId2);
                GetValues(config.SlaveId3);
                GetValues(config.SlaveId4);
            }
        }

        private void GetValues(byte slaveId)
        {
            byte[] res = modbus.ReadInputRegs(slaveId, 0, 2);
            if (res != null && res.Length == 4)
            {


                //温湿度
                //var temp= IntLib.GetIntFromByteArray(res,0);
                var temp=ShortLib.GetShortFromByteArray(res, 0);
                var humidity = ShortLib.GetShortFromByteArray(res, 2);
                //var temp = (res[0] * 256 + res[1]);
                //var humidity = (res[2] * 256 + res[3]);

                if (CurrentValue.ContainsKey(slaveId))
                {
                    CurrentValue[slaveId] = new ThMonitorDb()
                    {
                        TemperatureValue = temp,
                        HumidityValue = humidity
                    };
                }
                else
                {
                    CurrentValue.Add(slaveId, new ThMonitorDb()
                    {
                        TemperatureValue = temp,
                        HumidityValue = humidity
                    });
                }

            }
        }

        private Config GetIniValues()
        {
            Config config = new Config();
            filePath = fileName;
           // var portName= ReadIniData("串口参数", "端口号", "");
            config.PortName= ReadIniData("串口参数", "端口号", "");
            config.BaudRate=Convert.ToInt32( ReadIniData("串口参数", "波特率", ""));
            config.Parity =(Parity)Enum.Parse(typeof(Parity), ReadIniData("串口参数", "校验位", ""));
            config.DataBits= Convert.ToInt32(ReadIniData("串口参数", "数据位", ""));
            config.StopBits = (StopBits)Enum.Parse(typeof(StopBits), ReadIniData("串口参数", "停止位", ""));

            config.SlaveId1= Convert.ToByte(ReadIniData("站号参数", "站1", ""));
            config.SlaveId2 = Convert.ToByte(ReadIniData("站号参数", "站2", ""));
            config.SlaveId3 = Convert.ToByte(ReadIniData("站号参数", "站3", ""));
            config.SlaveId4 = Convert.ToByte(ReadIniData("站号参数", "站4", ""));

            return config;
        }
        private void picExit_Click(object sender, EventArgs e)
        {
            Close();
        }


        #region 窗体移动

        Point mPoint;


        private void panel2_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint = new Point(e.X, e.Y);
        }

        private void panel2_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button==MouseButtons.Left)
            {
                Location = new Point(Location.X + e.X - mPoint.X, Location.Y + e.Y - mPoint.Y);
            }
        }

        #endregion

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            cts?.Cancel();
        }

        private void picSetting_Click(object sender, EventArgs e)
        {
            FrmParamSet frm = new FrmParamSet(config);
            frm.ShowDialog();
        }
    }
}
